<script setup>
// 导入图片转换成为文件的api
import { imageUrlToFile } from '@/utils/imageUrlToFile.js'
import { ElMessage } from 'element-plus'

import { ref } from 'vue'

//导入获取用户信息的api
import { getUserIfo, userUpdateInfoService, userUploadAvatarService } from '@/api/user.js'
// 文件上传的处理
const imgUrl = ref('')

// 导入 icon ‘+‘ 符号
import { Plus } from '@element-plus/icons-vue'

// 一进入页面我就从后台渲染头像
const avatar = ref('')
const renderUserAtar = async() => {
    const res = await getUserIfo()
    avatar.value = res.data.data.user_pic
    imgUrl.value = avatar.value
}
renderUserAtar()


// 选择图片按钮
const uploadRef = ref()
const onUploadFile = (file) => {
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}

// 点击上传图片按钮
import { useUserStore } from '@/stores/modules/user.js'
const userStore = useUserStore()
const onUpdateAvatar = async () => {
  await userUploadAvatarService(imgUrl.value)
  await userStore.getUser() // 重新渲染一下最顶上的 小头像
  ElMessage({ type: 'success', message: '更换头像成功' })
}


</script>
<template>
    <PageContainer title="更换头像" >
      <el-row>
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <!-- 按钮 -->
        <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">
          选择图片
        </el-button>
        <el-button type="success" :icon="Upload" size="large" @click="onUpdateAvatar">
          上传头像
        </el-button>
      </el-col>
      </el-row>
    </PageContainer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}

</style>